package com.aipodcast.webbackend.service.impl;

import com.aipodcast.webbackend.entity.Users;
import com.aipodcast.webbackend.entity.req.LoginReq;
import com.aipodcast.webbackend.entity.req.RegisterReq;
import com.aipodcast.webbackend.entity.vo.UserVo;
import com.aipodcast.webbackend.mapper.UsersMapper;
import com.aipodcast.webbackend.service.IUsersService;
import com.aipodcast.webbackend.utils.ApiResponseUtils;
import com.aipodcast.webbackend.utils.ExceptionUtil;
import com.aipodcast.webbackend.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.catalina.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2025-09-22
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    private final PasswordEncoder encoder = new BCryptPasswordEncoder();

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public void register(String ip, RegisterReq registerReq) {
        if(baseMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getMobile, registerReq.getMobile())) != null) {
            throw new RuntimeException("手机号已存在");
        }
        try {
            Users users = new Users();
            users.setMobile(registerReq.getMobile());
            users.setPasswordHash(encoder.encode(registerReq.getPassword()));
            users.setNickname(registerReq.getNickname());
            users.setAvatarUrl(registerReq.getAvatarUrl());
            // 默认注册普通用户
            users.setRole(1);
            users.setStatus(1);
            users.setLastLoginIp(ip);
            users.setLastLoginTime(LocalDateTime.now());
            baseMapper.insert(users);
        }catch (Exception e) {
            ExceptionUtil.formatError("用户注册失败", e);
        }
    }

    @Override
    public String login(String ip, LoginReq loginReq) {
        Users users = baseMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getMobile, loginReq.getMobile()));
        if(users == null) {
            throw new RuntimeException("用户不存在");
        }
        if(!encoder.matches(loginReq.getPassword(), users.getPasswordHash())) {
            throw new RuntimeException("密码错误");
        }
        // 更新用户登录信息
        users.setLastLoginTime(LocalDateTime.now());
        users.setLastLoginIp(ip);
        baseMapper.updateById(users);
        // 生成token
        return jwtUtil.generateToken(users.getNickname(), users.getId(), users.getAvatarUrl(), users.getRole());

    }
}
